package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellData;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excelData.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;

import java.util.Map;

/**
 * 读取excel监听器
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduSubjectService service;

    public SubjectExcelListener(EduSubjectService service) {
        this.service = service;
    }
    public SubjectExcelListener(){}


    //读取一行
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext analysisContext) {
        //判断这行是不是空
        if (data == null) {
            throw new GuliException(20001,"添加失败");
        }

        //添加一级分类（第一列）
        EduSubject oneSubject=service.getByTitle(data.getOneSubjectName(), "0");//根据名称和父亲为0查是否已经存在
        if (oneSubject==null){
            //不存在重复则添加
            oneSubject = new EduSubject();
            oneSubject.setTitle(data.getOneSubjectName());
            oneSubject.setParentId("0");
            service.save(oneSubject);
        }

        //添加完取出自动生成的一级分类id
        String oneId= oneSubject.getId();

        //添加二级（第二列）,判断是否存在
        EduSubject twoSubject = service.getByTitle(data.getTwoSubjectName(), oneId);
        if (twoSubject==null){
            twoSubject = new EduSubject();
            twoSubject.setTitle(data.getTwoSubjectName());
            twoSubject.setParentId(oneId);
            service.save(twoSubject);
        }
    }

    //读完之后
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    @Override
    public void invokeHead(Map<Integer, CellData> headMap, AnalysisContext context) {
        System.out.println("表头信息:"+headMap);
    }
}
